from django.db import models
import hashlib
import os
import time
from django.utils.deconstruct import deconstructible



class BaseModel(models.Model):
    '''模型类的基类'''

    # auto_now_add 自管理字段
    create_time = models.DateTimeField(auto_now_add=True,
                                       verbose_name='创建时间')

    update_time = models.DateTimeField(auto_now_add=True,
                                       verbose_name='更新时间')

    class Meta:
        abstract = True




@deconstructible
class TimeStampFileName(object):
    def __init__(self, path):
        self.path = os.path.join(path, "%s")

    def __call__(self, instance, filename):
        extension = os.path.splitext(filename)[1]
        data = "%s_%d" % (filename, int(time.time()))
        file_hash = hashlib.sha1(data.encode("utf8")).hexdigest()
        time_dir = time.strftime("%Y/%m/", time.localtime())
        file_full_name = time_dir+ str(file_hash) + (extension)
        return self.path % (file_full_name)


@deconstructible
class ChatStampFileName(object):
    def __init__(self, path):
        self.path = os.path.join(path, "%s")

    def __call__(self, instance, filename):
        extension = os.path.splitext(filename)[1]
        data = "%s_%d" % (filename, int(time.time()))
        file_hash = hashlib.sha1(data.encode("utf8")).hexdigest()
        time_dir = time.strftime("%Y/%m/%d/", time.localtime())
        # file_full_name = time_dir+ str(file_hash) + (extension)
        file_full_name = time_dir+ str(file_hash) + '/'+ filename
        return self.path % (file_full_name)



@deconstructible
class IssueStampFileName(object):
    def __init__(self, path):
        self.path = os.path.join(path, "%s")

    def __call__(self, instance, filename):
        data = "%s_%d" % (filename, int(time.time()))
        file_hash = hashlib.sha1(data.encode("utf8")).hexdigest()
        time_dir = time.strftime("%Y/%m/%d/", time.localtime())
        file_full_name = time_dir+ str(file_hash) + '/'+ filename
        return self.path % (file_full_name)
